package com.bobo.serviceorder.lock;

import com.bobo.serviceorder.dao.TblOrderLockDao;
import com.bobo.serviceorder.entry.TblOrderLock;
import lombok.Data;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;

/**
 * @author bobo
 * @date 2021-04-12
 */
@Service
@Data
public class MysqlLock implements Lock {

    @Autowired
    private TblOrderLockDao orderLockDao;

    private ThreadLocal<TblOrderLock> orderLock;

    @Override
    public void lock() {
        // 尝试加锁
        if (tryLock()) {
            System.out.println("尝试加锁");
            return;
        }
        // 休眠10s
        try {
            Thread.sleep(10);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        // 递归继续加锁
        lock();

    }

    @Override
    public boolean tryLock() {
        try {
            TblOrderLock tblOrderLock = orderLock.get();
            orderLockDao.insert(tblOrderLock);
            System.out.println("加锁对象：" + tblOrderLock);
            return true;
        }catch (Exception e){
            return false;
        }
    }

    @Override
    public void unlock() {
        TblOrderLock tblOrderLock = orderLock.get();
        orderLockDao.deleteByPrimaryKey(tblOrderLock.getOrderId());
        System.out.println("解锁对象：" + tblOrderLock);
        orderLock.remove();
    }

    @Override
    public boolean tryLock(long time, TimeUnit unit) throws InterruptedException {

        return false;
    }

    @Override
    public void lockInterruptibly() throws InterruptedException {

    }

    @Override
    public Condition newCondition() {
        return null;
    }
}
